﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pai.LiveStation.Data;
using Microsoft.Security.Application;
namespace Pai.LiveStation.Web.Controllers
{
    public class BroadcastsController : Controller
    {
        //
        // GET: /Broadcasts/

        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Presidents")]
        public ActionResult Create()
        {
            return View();
        }

        [Authorize(Roles = "Presidents")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string name, string description, string releaseDate, string broadcastCollection, string broadcastType)
        {
            using (RadioClassesDataContext dc = new RadioClassesDataContext())
            {
                DateTime relDate;
                int broadType;
                if(!DateTime.TryParse(releaseDate, out relDate))
                {
                    ModelState.AddModelError("releaseDate", "Invalid Date");
                    return View();
                }
                if(!Int32.TryParse(broadcastType, out broadType))
                {
                    ModelState.AddModelError("broadcastType", "Invalid Broadcast Type");
                    return View();
                }
                Broadcast broadcast = new Broadcast()
                {
                    Name = AntiXss.HtmlEncode(name),
                    Description = AntiXss.HtmlEncode(description),
                    ReleaseDate = relDate,
                };

                if (String.IsNullOrEmpty(broadcastCollection))
                    ModelState.AddModelError("broadcastCollection", "There are no media items in the broadcast. Please add some items.");

                string[] broadcastItems = broadcastCollection.Split(';');
                broadcastItems.ToList<string>().ForEach(x =>
                {
                    string mediaKey = x.Substring(0, x.IndexOf('('));
                    short pref = Int16.Parse(x.Substring(x.IndexOf('(') + 1, x.Length - mediaKey.Length - 2));

                    int mediaID;
                    if(!Int32.TryParse(mediaKey, out mediaID))
                        ModelState.AddModelError("broadcastCollection", "Invalid media item.");
                    else
                    {
                        Media media = dc.Medias.Where(y => y.ID == mediaID).FirstOrDefault();
                        if (media == null)
                            ModelState.AddModelError("broadcastCollection", "Invalid media item.");
                        else
                        {
                            if (broadcast.BroadcastsMedias.Where(z => z.Media.ID == mediaID).FirstOrDefault() == null)
                                broadcast.BroadcastsMedias.Add(new BroadcastsMedia() { Broadcast = broadcast, Media = media, Rank = pref });
                        }
                    }
                });

                broadcast.BroadcastType = dc.BroadcastTypes.Where(x => x.ID == broadType).FirstOrDefault();

                if (ModelState.IsValid)
                    dc.SubmitChanges();

                return View();
            }
        }

        [Authorize(Roles = "Presidents")]
        public ActionResult Modify(string id)
        {
            using (RadioClassesDataContext dc = new RadioClassesDataContext())
            {
                int broadID;
                if(!Int32.TryParse(id, out broadID))
                {
                    ModelState.AddModelError("Error", "Invalid broadcast");
                    return View();
                }
                ViewData["Broadcast"] = dc.Broadcasts.Where(x => x.ID == broadID).FirstOrDefault();

                return View();
            }
        }

        [Authorize(Roles = "Presidents")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Modify(string id, string name, string description, 
            string releaseDate, string broadcastCollection, string broadcastType)
        {
            using (RadioClassesDataContext dc = new RadioClassesDataContext())
            {
                DateTime relDate;
                int broadType;
                int broadID;
                if (!DateTime.TryParse(releaseDate, out relDate))
                {
                    ModelState.AddModelError("releaseDate", "Invalid Date");
                    return View();
                }
                if (!Int32.TryParse(broadcastType, out broadType))
                {
                    ModelState.AddModelError("broadcastType", "Invalid Broadcast Type");
                    return View();
                }
                if(!Int32.TryParse(id, out broadID))
                {
                    ModelState.AddModelError("broadcastID", "Invalid Broadcast");
                    return View();
                }
                Broadcast broadcast = dc.Broadcasts.Where(x=>x.ID == broadID).FirstOrDefault();
                ViewData["Broadcast"] = broadcast;
                if(broadcast == null)
                {
                    ModelState.AddModelError("broadcastID", "Invalid Broadcast");
                    return View();
                }

                broadcast.Name = AntiXss.HtmlEncode(name);
                broadcast.Description = AntiXss.HtmlEncode(description);
                broadcast.ReleaseDate = relDate;
                

                if (String.IsNullOrEmpty(broadcastCollection))
                    ModelState.AddModelError("broadcastCollection", "There are no media items in the broadcast. Please add some items.");

                string[] broadcastItems = broadcastCollection.Split(';');
                broadcastItems.ToList<string>().ForEach(x =>
                {
                    string mediaKey = x.Substring(0, x.IndexOf('('));
                    short pref = Int16.Parse(x.Substring(x.IndexOf('(') + 1, x.Length - mediaKey.Length - 2));

                    int mediaID;
                    if (!Int32.TryParse(mediaKey, out mediaID))
                        ModelState.AddModelError("broadcastCollection", "Invalid media item.");
                    else
                    {
                        Media media = dc.Medias.Where(y => y.ID == mediaID).FirstOrDefault();
                        if (media == null)
                            ModelState.AddModelError("broadcastCollection", "Invalid media item.");
                        else
                        {
                            if(broadcast.BroadcastsMedias.Where(z=>z.Media.ID == mediaID).FirstOrDefault() == null)
                            broadcast.BroadcastsMedias.Add(new BroadcastsMedia() { Broadcast = broadcast, Media = media, Rank = pref });
                        }
                    }
                });

                broadcast.BroadcastType = dc.BroadcastTypes.Where(x => x.ID == broadType).FirstOrDefault();

                if (ModelState.IsValid)
                    dc.SubmitChanges();

                return View();
            }
        }

        [Authorize(Roles = "Members")]
        public ActionResult View(string id)
        {
            using (RadioClassesDataContext dc = new RadioClassesDataContext())
            {
                int broadID;
                if (!Int32.TryParse(id, out broadID))
                {
                    ModelState.AddModelError("Error", "Invalid broadcast");
                    return View();
                }
                ViewData["Broadcast"] = dc.Broadcasts.Where(x => x.ID == broadID).FirstOrDefault();

                return View();
            }
        }

        [Authorize(Roles = "Presidents")]
        public ActionResult Delete(string id)
        {
            using (RadioClassesDataContext dc = new RadioClassesDataContext())
            {
                int broadID;
                if (!Int32.TryParse(id, out broadID))
                {
                    ModelState.AddModelError("Error", "Invalid broadcast");
                    return View();
                }
                Broadcast broadcast = dc.Broadcasts.Where(x => x.ID == broadID).FirstOrDefault();
                
                if (broadcast == null)
                {
                    ModelState.AddModelError("Error", "Invalid broadcast");
                    return View();
                }


                dc.Broadcasts.DeleteOnSubmit(broadcast);

                dc.SubmitChanges();

                return View();
            }
        }
    }
}
